package com.zyb.system.logininfo.service.impl;

import com.zyb.system.logininfo.domain.LoginRO;
import com.zyb.system.logininfo.domain.LoginVO;
import com.zyb.system.logininfo.domain.Logininfo;
import com.zyb.system.logininfo.mapper.LogininfoMapper;
import com.zyb.system.logininfo.service.ILogininfoService;
import com.zyb.base.service.impl.BaseServiceImpl;
import com.zyb.utils.AjaxResult;
import com.zyb.utils.BusinessException;
import com.zyb.utils.MD5Utils;
import com.zyb.utils.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Arvin
 * @since 2023-02-01
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public AjaxResult account(LoginRO login) {
        if(login.getType() == null){
            throw new BusinessException("非法访问");
        }
        if(login.getUsername() == null || "".equals(login.getPassword().trim())){
            throw new BusinessException("用户名不能为空");
        }
        if(login.getPassword() == null || "".equals(login.getPassword().trim())){
            throw new BusinessException("密码不能为空");
        }
        Logininfo account = logininfoMapper.account(login);
        if(account == null){
            throw new BusinessException("用户名或者密码不能为空");
        }
        String password = login.getPassword();
        String salt = account.getSalt();//盐值
        String saltPassword = MD5Utils.encrypByMd5(salt + password);
        if(!account.getPassword().equals(saltPassword)){
            throw new BusinessException("用户名或者密码错误");
        }
        String token = StrUtils.getComplexRandomString(128);
        redisTemplate.opsForValue().set(token,account,30, TimeUnit.MINUTES);

        LoginVO loginVO = new LoginVO();
        loginVO.setToken(token);
        loginVO.setLogininfo(account);
        return AjaxResult.success().setData(loginVO).setMsg("managerLogin");
    }
}
